﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace WChat {
    public partial class WXTabContral : TabControl {
        Image backImage;
        private bool _haveCloseButton = false;
        private int _lastSelectIndex = -1;
        private int _selectIndex = 0;
        private int _mouse_over = -1;
        public delegate void tabCloseEventHandle(object sender, MouseEventArgs e);
        public event tabCloseEventHandle tabClose;
        private Timer flashTime = new Timer();//控制标签页闪烁的时间控件     
        Dictionary<string, string> TipTextDictionary = new Dictionary<string, string>();
        private bool _drawTipText = false;
        public WXTabContral() {
            setStyles();
           // backImage = new Bitmap(this.GetType(), "TabButtonBackground.bmp");   // 从资源文件（嵌入到程序集）里读取图片
            this.SizeMode = TabSizeMode.Fixed;  // 大小模式为固定
            this.ItemSize = new Size(44, 44);   // 设定每个标签的尺寸
            flashTime.Interval = 50;//控制呼吸灯效果的时间控件
            flashTime.Enabled = false;
            flashTime.Tick += new EventHandler(tabFlicker_timer_Tick);
            if (TabPages.Count > 0) _lastSelectIndex = 0;
            InitializeComponent();
        }
        public void tabFlicker_timer_Tick(object sender, EventArgs e) {
            base.Invalidate();
        }

        private void setStyles() {
            base.SetStyle(
                 ControlStyles.UserPaint |
                 ControlStyles.OptimizedDoubleBuffer |
                 ControlStyles.AllPaintingInWmPaint |
                 ControlStyles.ResizeRedraw |
                 ControlStyles.SupportsTransparentBackColor,
                 true);
            base.UpdateStyles();
        }

        [Category("外观")]
        [Description("是否绘制标签提示小字")]
        [DefaultValue(typeof(bool), "false")]
        public bool ShowDrawTipText {
            get { return _drawTipText; }
            set {
                _drawTipText = value;
                this.Padding = new Point(this.Padding.X, 4);
            }
        }

        /// <summary>
        /// 是否绘制关闭按钮
        /// </summary>
        [Category("外观")]
        [Description("是否绘制标签的关闭按钮")]
        [DefaultValue(typeof(bool), "false")]
        public bool HaveCloseButton {
            get { return _haveCloseButton; }
            set {
                _haveCloseButton = value;
                if (_haveCloseButton)    //绘制关闭按钮后对按钮周围空间量进行调整
                {
                    this.Padding = new Point(9, 3);
                }
                else { this.Padding = new Point(6, 3); }
            }
        }
     
        public void RemoveTabpage(string pagename) {
            TabPage checkTab = new TabPage(pagename);
            this.TabPages.Remove(checkTab);
        }
        /// <summary>
        /// 重写鼠标事件，鼠标在关闭区域点击时关闭选项卡
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseUp(MouseEventArgs e) {
            if (_haveCloseButton) {
                if (e.Button == MouseButtons.Left) {
                    Point cusorPoint = PointToClient(MousePosition);
                    //计算关闭区域  
                    Rectangle CloseRect = getCloseButtonRect(this.GetTabRect(SelectedIndex));
                    TabPage checkTab = this.SelectedTab;
                    //如果鼠标在区域内就关闭选项卡                      
                    if (CloseRect.Contains(cusorPoint)) {
                        if (tabClose != null)//移除选项卡之前执行tabclose事件，此事件在外部调用以在关闭标签时执行用户命令
                        { tabClose(this, e); }
                        SelectedIndex = _lastSelectIndex;      //此为设置选项卡为最后一次选择项，                 
                        this.TabPages.Remove(checkTab);
                        SelectIndexLog();
                    }
                }
            }
            base.OnMouseUp(e);
        }
        private void SelectIndexLog() {
            _lastSelectIndex = _selectIndex;
            _selectIndex = SelectedIndex;
        }
        /// <summary>
        /// 绘制关闭按钮
        /// </summary>
        /// <param name="g"></param>
        /// <param name="tabRect">标签的框体</param>
        /// <param name="cusorPoint">鼠标在工作区的相对坐标值</param>
        private void DrawCloseButton(Graphics g, Rectangle tabRect, Point cusorPoint) {
            Rectangle CBRect = getCloseButtonRect(tabRect);
            float i = 3.9F;
            float penWidth = 1.52F;
            Color lineColor = Color.FromArgb(200, 0, 0, 0);
            if (CBRect.Contains(cusorPoint)) {
                using (SolidBrush brush = new SolidBrush(Color.FromArgb(255, 255, 0, 0))) {

                    g.FillEllipse(brush, CBRect);
                }
                lineColor = Color.FromArgb(200, 255, 255, 255);//此句作用为在绘制背景小圆的时候对关闭十字颜色重设
                penWidth = 1.5F;
                using (Pen brush = new Pen(lineColor, penWidth)) {
                    g.DrawLine(brush, CBRect.X + i, CBRect.Y + i, CBRect.Right - i, CBRect.Bottom - i);
                    g.DrawLine(brush, CBRect.X + i, CBRect.Bottom - i, CBRect.Right - i, CBRect.Top + i);

                }
            }
           
        }

        /// <summary>
        /// 根据标签页矩形区，计算关闭按钮的矩形区
        /// </summary>
        /// <param name="tabRect">标签页矩形区</param>
        /// <returns>按钮矩形区</returns>
        private Rectangle getCloseButtonRect(Rectangle tabRect) {
            if (Alignment == TabAlignment.Top | Alignment == TabAlignment.Bottom) {
                tabRect.Offset(tabRect.Width - 19, tabRect.Height / 2 -23);
            }
            else if (Alignment == TabAlignment.Left) {
                tabRect.Offset(tabRect.Width / 2 - 8, 7);
            }
            else if (Alignment == TabAlignment.Right) {
                tabRect.Offset(tabRect.Width / 2 - 7, tabRect.Height - 21);
            }
            tabRect.Height = 15;
            tabRect.Width = 15;
            return tabRect;
        }
        //重绘方法
        protected override void OnPaint(PaintEventArgs e) {
            DrawDrawBackgroundAndHeader(e.Graphics);
            for (int i = 0; i < this.TabCount; i++) {
                Rectangle bounds = this.GetTabRect(i);
                TabPage page = TabPages[i];
                Point cusorPoint = PointToClient(MousePosition);
                if (this.SelectedIndex == i) {
                    e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(112, 176, 196, 222)), bounds);    //则绘制颜色
                    //e.Graphics.DrawImage(backImage, this.GetTabRect(i));
                }
                Point temPoint = new Point(cusorPoint.X, cusorPoint.Y);

                if (this.ImageList != null&& this.ImageList.Images.Count!=0) {
                    int index = this.TabPages[i].ImageIndex;  //获取在主界面给定的头像索引值
                    string key = this.TabPages[i].ImageKey;
                    Image icon = new Bitmap(45, 45);

                    if (index > -1) {
                        if (this.ImageList.Images[index]!=null) {//如果图片数组的第xx位有图片
                            icon = this.ImageList.Images[index];  //将图片数组的第xx位图片赋值给icon（这里出现报错）
                            Bitmap b = WayOne(icon);
                            //绘制圆形图片
                            e.Graphics.DrawImage(b, bounds.X + (bounds.Width - icon.Width) / 2, (bounds.Y + (bounds.Height - icon.Height) / 2) - 6);
                            //绘制圆形圈
                            using (Pen p = new Pen(Color.GreenYellow, 2)) {
                                e.Graphics.DrawEllipse(p, bounds.X + (bounds.Width - icon.Width) / 2, (bounds.Y + (bounds.Height - icon.Height) / 2) - 6, icon.Width, icon.Height);
                            }
                            //using (Graphics g = Graphics.FromImage(icon)) {
                            //    e.Graphics.FillEllipse(new TextureBrush(icon), bounds.X + (bounds.Width - icon.Width) / 2, bounds.Y + (bounds.Height - icon.Height) / 2, icon.Width, icon.Height);
                            //}
                            if (!string.IsNullOrEmpty(key)) {
                                icon = this.ImageList.Images[key];
                                Bitmap bs = WayOne(icon);
                                //绘制圆形图片
                                e.Graphics.DrawImage(bs, bounds.X + (bounds.Width - icon.Width) / 2, (bounds.Y + (bounds.Height - icon.Height) / 2) - 6);
                                //绘制圆形圈
                                using (Pen p = new Pen(Color.GreenYellow, 2)) {
                                    e.Graphics.DrawEllipse(p, bounds.X + (bounds.Width - icon.Width) / 2, (bounds.Y + (bounds.Height - icon.Height) / 2) - 6, icon.Width, icon.Height);
                                }
                            }
                    }
                }
                        //  e.Graphics.DrawImage(icon, bounds.X + (bounds.Width - icon.Width) / 2, bounds.Y + (bounds.Height - icon.Height) / 2);
              }

                if (ShowDrawTipText & TipTextDictionary.ContainsKey(page.Name)) {
                    if (TipTextDictionary[page.Name] != null) {
                        string text = TipTextDictionary[page.Name];
                        if (text != "")

                            using (Font f3 = new Font("微软雅黑", 8))  //未读消息小红圆点
                            {
                                e.Graphics.FillEllipse(Brushes.Red, new Rectangle(bounds.X, bounds.Y, 15, 15));
                                e.Graphics.DrawString(text, f3, Brushes.White, new PointF(bounds.X + 2, bounds.Y + 1));
                            }
                    }
                }
                if (HaveCloseButton) {   //如果当前鼠标落在该行上
                    DrawCloseButton(e.Graphics, bounds, temPoint);
                }
               
                PointF textPoint = new PointF();
                SizeF textSize = TextRenderer.MeasureText(this.TabPages[i].Text, this.Font);
                textPoint.X = bounds.X + (bounds.Width - textSize.Width) / 2;  // 注意要加上每个标签的左偏移量X  
                textPoint.Y = bounds.Bottom - textSize.Height - this.Padding.Y;
                e.Graphics.DrawString(this.TabPages[i].Text, this.Font, SystemBrushes.ControlLightLight, textPoint.X, textPoint.Y);
            // e.Graphics.DrawString(this.TabPages[i].Text, this.Font,SystemBrushes.ControlText,textPoint.X, textPoint.Y);  // 正常颜色   
            }
        }

        protected override void OnSelectedIndexChanged(EventArgs e) {
            SelectIndexLog();
            if (TabPages.Count > 0 & SelectedTab != null) {
                if (TipTextDictionary.ContainsKey(SelectedTab.Name)) {
                    TipTextDictionary.Remove(SelectedTab.Name);
                }
            }
            else if (TabPages.Count <= 0) {
                TipTextDictionary.Clear();
            }
            base.OnSelectedIndexChanged(e);
        }

        // 将需要显示的Tip文字添加到容器以显示
        public void TipTextAdd(string tabPageName, string text) {
            flashTime.Enabled = true;
            if (SelectedTab != null) {
                if (SelectedTab.Name == tabPageName)    //不对当前标签添加Tip文字
                { return; }
            }
            if (TabPages.ContainsKey(tabPageName)) {
                if (!TipTextDictionary.ContainsKey(tabPageName)) {
                    TipTextDictionary.Add(tabPageName, text);
                }
                else {
                    TipTextDictionary[tabPageName] = text;
                }
            }
        }

        private Bitmap WayOne(Image img) {
            using (Image i = new Bitmap(img)) {
                Bitmap b = new Bitmap(i.Width, i.Height);
                using (Graphics g = Graphics.FromImage(b)) {
                    g.FillEllipse(new TextureBrush(i), -1, 0, i.Width, i.Height);
                }
                return b;
            }
        }
        private void DrawDrawBackgroundAndHeader(Graphics g) {
            int x = 0;
            int y = 0;
            int width = 0;
            int height = 0;
            switch (Alignment) {
            case TabAlignment.Top:
            x = 0;
            y = 0;
            width = ClientRectangle.Width;
            height = ClientRectangle.Height - DisplayRectangle.Height;
            break;
            case TabAlignment.Bottom:
            x = 0;
            y = DisplayRectangle.Height;
            width = ClientRectangle.Width;
            height = ClientRectangle.Height - DisplayRectangle.Height;
            break;
            case TabAlignment.Left:
            x = 0;
            y = 0;
            width = ClientRectangle.Width - DisplayRectangle.Width;
            height = ClientRectangle.Height;
            break;
            case TabAlignment.Right:
            x = DisplayRectangle.Width;
            y = 0;
            width = ClientRectangle.Width - DisplayRectangle.Width;
            height = ClientRectangle.Height;
            break;
            }
            //标签所在的矩形
            Rectangle bodyRect = new Rectangle(x, y, ClientRectangle.Width /4, ClientRectangle.Height+3);
            Rectangle headerRect = new Rectangle(x, y, width, height-4);
            Color backColor = Enabled ? Color.FromArgb(255, 45, 54, 63) : SystemColors.Control;
            Color headbackColor = Enabled ? Color.Black : SystemColors.Control;
            using (SolidBrush brush = new SolidBrush(backColor)) {
                g.FillRectangle(brush, bodyRect);
            }
            using (SolidBrush brush = new SolidBrush(headbackColor)) {
                g.FillRectangle(brush, headerRect);
            }
        }

    }
}

  